import {common} from '../model/endpoints';

  
/**
 * 给 m 前面补 0 保证长度为 n
 * @param {number} m
 * @param {number} n
 */
export function pad(m, n) {
    return (Array(n).join('0') + m).slice(-n);
}

/**
 * 格式化时间戳为年月日
 * @param {string|number} timestamp
 */
export function formatTimestampToYmd(timestamp) {
    if (!timestamp) return timestamp;
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${pad(date.getMonth() + 1, 2)}-${pad(
        date.getDate(),
        2
    )}`;
}

/**
 * URLSearchParams
 * @param {string} searchParams
 */
function parseByURLSearchParams(searchParams) {
    searchParams = new URLSearchParams(searchParams);

    let searchParamsJson = {};
    for (let params of searchParams) {
        searchParamsJson[params[0]] = decodeURIComponent(params[1]);
    }
    return searchParamsJson;
}

/**
 * replace -> parse
 * @param {string} searchParams
 */
function parseByReplace(searchParams) {
    searchParams = searchParams.replace(/&|=/g, m => {
        if (m === '&') {
            return '", "';
        } else if (m === '=') {
            return '": "';
        }
    });
    return searchParams ? JSON.parse(`{"${searchParams}"}`) : {};
}

/**
 * 格式化 url 的参数为 json
 * @param {string} url
 */
export function parseUrlToJson(url) {
    if (typeof url !== 'string') {
        console.warn('传入合法 Url 参数');
        return;
    }
    let searchParams;
    if (/\?/.test(url)) {
        searchParams = url.split('?')[1];
    } else {
        return {};
    }

    if (typeof URLSearchParams !== 'undefined') {
        return parseByURLSearchParams(searchParams);
    }
    return parseByReplace(searchParams);
}


/**
 * 上传图片
 * @param {*} path 
 * @param {*} uploadUrl  图片上传路径
 * @returns 
 */
export const uploadFile  = (path, uploadUrl) => {
    const token = wx.getStorageSync('token');
    if(!token){
        wx.switchTab({
            url: '/pages/index/index',
        });
    }
    return new Promise((resolve, reject) => {
        wx.uploadFile({
            url: uploadUrl || (common + '/upload'),
            filePath: path,
            name: 'file',
            formData: { },
            header: {
                token,
                'Content-Type': 'multipart/form-data',
            },
            success: (res) => {
                console.log(res);
                if (res.statusCode === 200) {
                    resolve(res.data);
                }
            },
            fail: (err) => {
                reject(err);
            }
        });
    });
};


/**
 * 根据屏幕分辨率 rpx 转 实际px
 * 以 750 为标准
 * @param {*} rpx
 * @returns
 */
export const rpxToPx = function (rpx) {
    const systemInfo = wx.getSystemInfoSync();
    const width = systemInfo.screenWidth;
    rpx = Number(rpx);
    return width ? (width / 750) * rpx : rpx;
};